import qdrant_client
from typing import Any,List
from abc import  abstractmethod
from qdrant_client.http.models import Distance, VectorParams
from langchain.schema import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.qdrant import Qdrant


class MyVectorStore:
    def __init__(self,embeddings:Embeddings,collection_name:str):
        self.embeddings=embeddings
        self.collection_name=collection_name
    

    def create_collection(self,collection_name:str)->bool:
        return self._create_collection(collection_name=collection_name)
    
    def create_docments(self,documents:List[Document])->None:
        self._add_docments(documents=documents)

    def add_docments(self,documents:List[Document])->List[str]:
        return self._add_docments(documents=documents)

    def delte_docment_by_ids(self,ids:List[str]):
        return self._delte_docment_by_ids(ids=ids)

    @abstractmethod
    def _create_collection(self,collection_name:str)->bool:
        """返回是否创建成功集合桶"""

    @abstractmethod
    def _add_docments(self,documents:List[Document])->List[str]:
        """保存文档对象"""
    
    @abstractmethod
    def _delte_docment_by_ids(self,ids:List[str])->bool:
        """保存文档对象"""

class QdrantVectorStore(MyVectorStore):
    def __init__(self,url:str,**kwargs):
        super().__init__(**kwargs)
        self.url=url
        client = qdrant_client.QdrantClient(
            url=self.url,
            prefer_grpc=False
        )
        try:
            client.create_collection(
                collection_name=self.collection_name,
                vectors_config=VectorParams(size=1024, distance=Distance.COSINE)
            )
        except Exception as e:
            print("向量库创建异常：",str(e))
        self.qdrant=Qdrant(
                client=client,
                collection_name=self.collection_name,
                embeddings=self.embeddings,
        )
    def _create_collection(self,collection_name:str)->bool:
        return self.qdrant.client.create_collection(
            collection_name="collection_name",
            vectors_config=VectorParams(size=1024, distance=Distance.COSINE)
        )
    
    def _add_docments(self,documents:List[Document])->List[str]:
        return self.qdrant.add_documents(documents=documents)
    
    def _delte_docment_by_ids(self,ids:List[str])->bool:
        return self.qdrant.delete(ids)

    def search_document(self,text:str,k=3,score_threshold=0.5)->List[Document]:
        results= self.qdrant.similarity_search_with_relevance_scores(query=text,k=k)
        documents=[]
        for result in results:
            document,score=result
            print("【当前分数为：】",score)
            if score>=score_threshold:
                documents.append(document)
        return documents
    
